<template>
  <div>
    <!-- 添加菜品按钮 -->
    <el-card shadow="hover" body-style="width:100%;" style="margin-bottom: 20px" >
    <el-button
      type="primary"
      icon="el-icon-plus"
      style="margin: 10px 0"
      @click="showDialog"
    >添加蛋糕</el-button>
    </el-card>
    <!-- 菜品列表展示 -->
    <el-card shadow="hover" body-style="width:100%;" style="margin-bottom: 20px">
    <el-table :data="foodList" style="width: 100%" border stripe :header-cell-class-name="'headerBg'">
      <el-table-column label="序号" width="60" align="center" type="index" />
      <el-table-column prop="prop" label="蛋糕图片" width="125px">
        <template slot-scope="scope">
          <img :src="scope.row.imgSrc" width="100px" height="100px">
        </template>
      </el-table-column>
      <el-table-column prop="name" label="蛋糕名称" width="width" />
      <el-table-column prop="categoryName" label="蛋糕分类" width="100px" />
      <el-table-column prop="price" label="价格" width="80px">
        <template slot-scope="scope">
          ¥ {{ scope.row.price | rounding }}
        </template>
      </el-table-column>
      <el-table-column prop="description" label="菜品描述" width="width" />
      <el-table-column prop="isRecommend" label="今日推荐" width="width">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isRecommend"
            active-text="推荐"
            @change="updateRecommend(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="200px" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="warning"
            icon="el-icon-edit"
            size="mini"
            @click="updateFood(scope.row)"
          >修改</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteFood(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <el-pagination
      style="margin-top: 20px; textalign: center"
      :current-page="pageParams.page"
      :page-sizes="[3, 5, 10]"
      :page-size="pageParams.pageSize"
      :pager-count="4"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="pageParams.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 添加||修改菜品的弹窗 -->
    <el-dialog
      :title="foodForm.id ? '修改蛋糕' : '添加蛋糕'"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="ruleForm"
        :model="foodForm"
        style="width: 80%"
        :rules="rules"
      >
        <el-form-item label="蛋糕名称" prop="name">
          <el-input v-model="foodForm.name" />
        </el-form-item>
        <!-- 下拉框选择分类 -->
        <el-form-item label="分类" prop="categoryId">
          <br>
          <el-select
            v-model="foodForm.categoryId"
            placeholder="请选择蛋糕分类"
            style="width: 100%"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="蛋糕价格" prop="price">
          <el-input v-model="foodForm.price" />
        </el-form-item>
        <el-form-item label="蛋糕描述" prop="description">
          <el-input v-model="foodForm.description" />
        </el-form-item>
        <!-- 上传图片组件-->
        <el-form-item label="菜品图片" prop="imgSrc">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="foodForm.imgSrc" :src="foodForm.imgSrc" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCheckedForm">确 定</el-button>
      </div>
    </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'FoodList',
  filters: {
    rounding(value) {
      return value.toFixed(2)
    }
  },
  data() {
    return {
      dialogFormVisible: false,
      // 新增|修改获取的表单数据
      foodForm: {
        name: '',
        categoryId: '',
        categoryName: '',
        price: 0,
        imgSrc: '',
        description: ''
      },
      showSrc: '',
      // 菜品列表
      foodList: [],
      // 分类列表 包含{id,name}  参照options数组
      categoryList: [],
      // 分页参数
      pageParams: {
        page: 1,
        pageSize: 5,
        total: 0
      },
      // 表单验证
      rules: {
        name: [
          { required: true, message: '请输入菜品名字', trigger: 'blur' },
          { min: 1, message: '名字至少一个字', trigger: 'change' }
        ],
        categoryId: [
          { required: true, message: '请选择菜品分类', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入菜品价格' },
          {
            pattern:
              /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '请输入正确的价格',
            trigger: 'change'
          }
        ],
        description: [{ required: true, message: '请输入菜品描述' }],
        imgSrc: [{ required: true, message: '请上传菜品图片' }]
      }
    }
  },
  mounted() {
    this.getFoodList()
    // 用于添加|修改菜品的时候分类展示用的
    this.getCateList()
  },
  methods: {
    // 获取菜品分类,用于添加或者修改
    async getCateList() {
      const res = await this.$API.catelist.reqCateList()
      if (res.code === 200) {
        this.categoryList = res.data
      }
    },
    // 获取菜品列表
    async getFoodList() {
      const res = await this.$API.foodlist.reqFoodList(this.pageParams)
      if (res.code === 200) {
        this.pageParams.total = res.data.total
        this.foodList = res.data.foodVoList
      }
    },
    // 显示添加|修改菜品
    showDialog() {
      // 显示对话框
      this.dialogFormVisible = true
      // 如果点了取消会清空数据，每次打开都会为空
      this.foodForm = {
        name: '',
        categoryId: '',
        categoryName: '',
        price: 0,
        imgSrc: '',
        description: ''
      }
    },
    // 更新菜品信息
    updateFood(row) {
      console.log('点击了修改菜品信息按钮', row)
      this.dialogFormVisible = true
      // foodForm存储的服务器返回的数据,这个地方是深拷贝{...row}
      this.foodForm = { ...row }
    },
    // 更新菜品,是否推荐
    updateRecommend(row) {
      console.log('修改了是否推荐', row.isRecommend)
      // 给提交的表单赋值
      this.foodForm = { ...row }
      this.addOrUpdateFood()
    },
    deleteFood(row) {
      this.$confirm('是否删除该菜品？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const res = await this.$API.foodlist.reqRemoveFood(row.id)
          if (res.code === 200) {
            this.$message.success('删除成功!')
            this.getFoodList()
          }
        })
        .catch(() => {
          this.$message({
            type: 'warning',
            message: '你取消了删除'
          })
        })
    },
    // 验证表单之后提交
    submitCheckedForm() {
      this.$refs.ruleForm.validate((success) => {
        if (success) {
          this.addOrUpdateFood()
        } else {
          this.$message.error('提交表单失败')
          return false
        }
      })
    },
    // 这个可以用于修改今日推荐
    async addOrUpdateFood() {
      this.dialogFormVisible = false
      const res = await this.$API.foodlist.reqAddOrUpdateFood(this.foodForm)
      console.log('@@@@@addorupdate--res', res)

      if (res.code === 200) {
        // 有id 修改成功 没有id 添加成功
        this.$message.success(
          this.foodForm.id ? '修改菜品成功' : '添加菜品成功'
        )

        this.getFoodList()
      }
    },
    // 上传图片前后函数
    handleAvatarSuccess(res, file) {
      this.foodForm.imgSrc = res.data
      this.showSrc = res.data
      console.log('@@@@handleAvatarSuccess-res', res)
      console.log('@@@@handleAvatarSuccess-file', file)
    },
    beforeAvatarUpload(file) {
      // console.log("@@@输出上传之前的file", file);
      // const isJPG = file.type === "image/jpeg";
      // const isLt2M = file.size / 1024 / 1024 < 2;

      // if (!isJPG) {
      //   this.$message.error("上传头像图片只能是 JPG 格式!");
      // }
      // if (!isLt2M) {
      //   this.$message.error("上传头像图片大小不能超过 2MB!");
      // }
      // return isJPG && isLt2M;
    },
    // 分页函数
    handleSizeChange(newPageSize) {
      this.pageParams.pageSize = newPageSize
      this.getFoodList()
    },
    handleCurrentChange(current) {
      this.pageParams.page = current
      this.getFoodList()
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.headerBg {
  background: #eee!important;
}
</style>

